﻿using Awsc.DataAcquisitionSys.Core.Model.Config;
using Awsc.DataAcquisitionSys.Core.Models.ServiceModels;
using Awsc.DataAcquisitionSys.Core.Services.DataAcquisition.DataCollectors;
using System.Net.Sockets;


namespace Awsc.DataAcquisitionSys.Core.Service.DataAcquisition.DataCollectors
{
    public abstract class TcpDataCollector : DataCollector
    {
        protected TcpClient TcpClient { get; set; }
        protected NetworkStream TcpStream { get; set; }

        public TcpDataCollector(DataCollectionContext dataCollectionContext) : base(dataCollectionContext)
        {
            TcpClient = new TcpClient();
        }

        public async override Task CollectSensorDataAsync()
        {
            try
            {
                if (TcpClient.Connected && TcpStream != null)
                {
                    //修改采集器状态
                    Status = DevStatus.S_OK;
                    await CollectDataInternalAsync();

                }
                else
                {
                    TcpStream?.Close();
                    //socket重新连接
                    Status = DevStatus.S_OFFLINE;
                    Connect();
                }
            }
            catch (Exception ex)
            {
                if (TcpClient != null)
                {
                    TcpStream?.Close();
                    TcpClient.Close();
                }
                Status = DevStatus.S_ERR;
            }
        }

        protected abstract Task CollectDataInternalAsync();


        public override void Connect()
        {
            try
            {

                TcpClient.Connect(CollectorConfig.IP, CollectorConfig.Port);
                if (TcpClient.Connected)
                {
                    TcpStream = TcpClient.GetStream();
                    TcpClient.Client.Blocking = true;
                    TcpClient.Client.ReceiveTimeout = 500;
                }
            }
            catch (Exception ex)
            {
                Status = DevStatus.S_ERR;


            }
        }
        public override void CloseConnection()
        {
            if (TcpClient != null)
            {
                TcpClient.Client.Close();
                TcpClient.Close();
            }
            TcpClient = null;
        }

    }
}
